package com.pdd.account.tourist.server.commons.util;

import com.pdd.account.tourist.enums.WebResultEmun;
import com.pdd.account.tourist.response.ResponseResult;
import com.pdd.commons.response.ResponseEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

/**
 * @author:liyangpeng
 * @date:2019/7/3 18:07
 */
@Component
@Slf4j
public class MailUtil {
    @Autowired
    private JavaMailSender sender;

    /**
     * 发送邮件验证码
     * @param to
     * @param subject
     * @param code
     */
    public ResponseEntity sendMailValidCode(String to, String subject, String code){
        MimeMessage message=sender.createMimeMessage();
        try {
            StringBuffer buffer=new StringBuffer();
            buffer.append("<p>您的邮箱验证码为："+code+"，如非本人操作请忽略.</p>");
            MimeMessageHelper helper=new MimeMessageHelper(message,true);
            helper.setFrom(new InternetAddress("3334783376@qq.com",subject,"UTF-8"));
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(buffer.toString(),true);
            sender.send(message);
            return ResponseResult.Return(WebResultEmun.EMAIL_SEND_SUCCESS);
        }catch (Exception e){
            log.error("【pdd博客】邮件发送失败:{}",e);
        }
        return ResponseResult.Return(WebResultEmun.EMAIL_SEND_ERROR);
    }
}
